/**
 * @author David Young
 */
package csab.core;

import java.util.Collection;
import java.util.HashMap;

/**
 * This class is an inventory designed to hold various inventory items.
 * @author David Young
 */
public class Inventory {
	private HashMap<Integer, Item> items;
	private int curritems;
	private int maxitems;
	
	/**
	 * Inventory constructor.
	 * @param maxitems The maximum number of items
	 * this Inventory can contain. Set to 0 if this
	 * Inventory system can carry "infinite" items.
	 */
	public Inventory(int maxitems)
	{
		if(maxitems > 0)
			items = new HashMap<Integer, Item>(maxitems);
		else
			items = new HashMap<Integer, Item>();
		
		this.curritems = 0;
		this.maxitems = maxitems;
	}
	
	/**
	 * Add an Item to this Inventory.
	 * @param itm The Item to add.
	 * @see csab.core.Item
	 */
	public void addItem(Item itm)
	{
		if(maxitems == 0 || curritems < maxitems)
		{
			itm.setDrawable(false);
			itm.setCanCollide(false);
			curritems++;
			items.put(itm.getID(), itm);
		}
	}
	
	/**
	 * Return a Collection of all Item objects in
	 * this inventory.
	 * @return The Collection that enumerates all
	 * Item objects in this inventory.
	 * @see java.util.Collection
	 * @see csab.core.Item
	 */
	public Collection<Item> getItems()
	{
		return items.values();
	}
	
	/**
	 * Remove and return all Item objects within
	 * this Inventory.
	 * @return The enumeration of all the removed
	 * Item objects in this Inventory.
	 * @see java.util.Collection
	 * @see csab.core.Item
	 */
	public Collection<Item> removeAllItems()
	{
		Collection<Item> collection = items.values();
		items.clear();
		curritems = 0;
		return collection;
	}
	
	/**
	 * Remove a single Item from this Inventory.
	 * @param itm The Item object to remove.
	 * @see csab.core.Item
	 */
	public void removeItem(Item itm)
	{
		if(items.containsKey(itm.getID()))
		{
			curritems--;
			items.remove(itm.getID());
		}
	}
	
	/** 
	 * Perform a use operation on a Sprite by an
	 * Item contained within this Inventory.
	 * @param obj The Sprite to apply the operation to.
	 * @param itm The Item to use.
	 * @return true if the Item is used.
	 */
	public boolean useInventoryItem(Sprite obj, Item itm)
	{
		if(!items.containsKey(itm.getID()) || itm.getUses() <= 0)
		{
			if(itm.getUses() <= 0) 
			{
				items.remove(itm.getID());
				curritems--;
			}
			return false;
		}
		else 
		{
			boolean rtn = itm.useItem(obj);
			if(itm.getUses() <= 0)
			{
				items.remove(itm.getID());
				curritems--;
			}
			
			return rtn;
		}
	}
}
